import { useState, useEffect } from 'react';
import { FolderPlus } from 'lucide-react';
import type { VideoGenerateRequest } from '../../types/video';
import { folderApi } from '../../api';
import { toast } from '../../stores/toastStore';

interface Folder {
  id: string;
  name: string;
  parent_id?: string;
}

interface SettingsTabProps {
  formData: VideoGenerateRequest;
  onChange: (data: Partial<VideoGenerateRequest>) => void;
}

export default function SettingsTab({ formData, onChange }: SettingsTabProps) {
  const [folders, setFolders] = useState<Folder[]>([]);
  const [loading, setLoading] = useState(false);
  const [showNewFolder, setShowNewFolder] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [creating, setCreating] = useState(false);

  // 加载文件夹列表
  useEffect(() => {
    loadFolders();
  }, []);

  const loadFolders = async () => {
    try {
      setLoading(true);
      const folderList = await folderApi.getFolders();
      setFolders(folderList);
    } catch (error) {
      console.error('Failed to load folders:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateFolder = async () => {
    if (!newFolderName.trim()) return;

    try {
      setCreating(true);
      const newFolder = await folderApi.createFolder({ name: newFolderName.trim() });
      setFolders(prev => [...prev, newFolder]);
      setNewFolderName('');
      setShowNewFolder(false);
      // 自动选择新建的文件夹
      onChange({ folder_id: newFolder.id });
    } catch (error) {
      console.error('Failed to create folder:', error);
      toast.error('创建文件夹失败');
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <label className="block text-sm font-semibold text-gray-800 mb-2">视频比例</label>
        <select
          value={formData.aspect_ratio}
          onChange={e =>
            onChange({
              aspect_ratio: e.target.value as '16:9' | '9:16' | '1:1',
            })
          }
          className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900"
        >
          <option value="16:9">16:9 (横屏)</option>
          <option value="9:16">9:16 (竖屏)</option>
          <option value="1:1">1:1 (正方形)</option>
        </select>
      </div>

      <div>
        <label className="block text-sm font-semibold text-gray-800 mb-2">背景设置</label>
        <div className="space-y-4">
          {/* 背景类型选择 */}
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => onChange({ background: '' })}
              className={`px-3 py-1 text-xs rounded ${
                !formData.background
                  ? 'bg-blue-100 text-blue-700'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              默认
            </button>
            <button
              type="button"
              onClick={() => onChange({ background: '#ffffff' })}
              className={`px-3 py-1 text-xs rounded ${
                formData.background?.startsWith('#')
                  ? 'bg-blue-100 text-blue-700'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              纯色
            </button>
            <button
              type="button"
              onClick={() => onChange({ background: 'https://example.com/bg.jpg' })}
              className={`px-3 py-1 text-xs rounded ${
                formData.background?.startsWith('http')
                  ? 'bg-blue-100 text-blue-700'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              图片
            </button>
          </div>

          {/* 颜色选择器 */}
          {formData.background?.startsWith('#') && (
            <div className="flex gap-2 items-center">
              <input
                type="color"
                value={formData.background}
                onChange={e => onChange({ background: e.target.value })}
                className="w-12 h-8 rounded border cursor-pointer"
              />
              <input
                type="text"
                value={formData.background}
                onChange={e => onChange({ background: e.target.value })}
                placeholder="#ffffff"
                className="flex-1 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 text-sm"
              />
            </div>
          )}

          {/* 图片URL输入 */}
          {formData.background?.startsWith('http') && (
            <input
              type="url"
              value={formData.background}
              onChange={e => onChange({ background: e.target.value })}
              placeholder="https://example.com/background.jpg"
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 text-sm"
            />
          )}

          {/* 预设颜色 */}
          <div>
            <p className="text-xs text-gray-600 mb-2">快速选择：</p>
            <div className="flex gap-2 flex-wrap">
              {[
                '#ffffff',
                '#000000',
                '#f3f4f6',
                '#ddd6fe',
                '#fef3c7',
                '#fce7f3',
                '#d1fae5',
                '#dbeafe',
              ].map(color => (
                <button
                  key={color}
                  type="button"
                  onClick={() => onChange({ background: color })}
                  className="w-8 h-8 rounded border-2 border-gray-300 hover:border-gray-400 transition-colors"
                  style={{ backgroundColor: color }}
                  title={color}
                />
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* 文件夹选择 */}
      <div>
        <div className="flex items-center justify-between mb-2">
          <label className="block text-sm font-semibold text-gray-800">输出文件夹</label>
          <button
            type="button"
            onClick={() => setShowNewFolder(!showNewFolder)}
            className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded transition-colors"
          >
            <FolderPlus className="w-3 h-3" />
            新建文件夹
          </button>
        </div>

        {showNewFolder && (
          <div className="mb-3 p-3 bg-gray-50 rounded-lg border">
            <div className="flex gap-2">
              <input
                type="text"
                value={newFolderName}
                onChange={e => setNewFolderName(e.target.value)}
                placeholder="文件夹名称"
                className="flex-1 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 text-sm"
                onKeyPress={e => e.key === 'Enter' && handleCreateFolder()}
              />
              <button
                type="button"
                onClick={handleCreateFolder}
                disabled={creating || !newFolderName.trim()}
                className="px-3 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {creating ? '创建中...' : '创建'}
              </button>
            </div>
          </div>
        )}

        <select
          value={formData.folder_id || ''}
          onChange={e => onChange({ folder_id: e.target.value || undefined })}
          disabled={loading}
          className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 text-sm"
        >
          <option value="">默认文件夹</option>
          {folders.map(folder => (
            <option key={folder.id} value={folder.id}>
              {folder.name}
            </option>
          ))}
        </select>
        <p className="mt-1 text-xs text-gray-600">
          选择文件夹来组织生成的视频，留空则使用默认文件夹
        </p>
      </div>
    </div>
  );
}
